package xyz.xiaomeiqiu.netty.outbound;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {

    private final boolean daemon;
    private final String prefix;
    private final ThreadGroup threadGroup;
    private final AtomicInteger threadNumber = new AtomicInteger(1);


    public NamedThreadFactory(String proxyService, boolean daemon) {
        this.daemon = daemon;
        SecurityManager securityManager = System.getSecurityManager();
        this.threadGroup = (securityManager!=null)?securityManager.getThreadGroup():Thread.currentThread().getThreadGroup();
        this.prefix = proxyService;
    }

    public NamedThreadFactory(String proxyService) {
        this(proxyService, false);
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r, prefix+"-thread-"+threadNumber.getAndIncrement(), 0);
        t.setDaemon(this.daemon);
        return t;
    }
}
